package com.ruoyi.project.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.order.domain.HisCareHistory;
import com.ruoyi.project.order.domain.HisCareOrderItem;
import com.ruoyi.project.order.domain.HisOrderCharge;
import com.ruoyi.project.order.domain.HisOrderChargeItem;
import com.ruoyi.project.order.service.HisOrderPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


@Controller

public class OrderPayController {

    @Autowired
    private HisOrderPayService payService;

    //创建支付宝支付需要的常量值

    // 应用标识， 需要使用支付宝扫码登录《支付宝沙箱环境地址》中查看
    private final String APP_ID = "2021000118608107";
    // 应用私钥， 需要安装支付宝开放平台助手，在助手中---生成密钥 找
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCFtHUNOdtXxXVT9VyaGT5uLIXULbXrj0VZ5m90N2drafltz9khug4KmGxoI6eRGMmOXaqsVi9DBHuWkSASHZmtO/ZaE8zSt99ajCE/EcCY0GIc8mM3XlFW18ki59YcvayEd1cFEqh43BRV9Iea2RxQyUdsQWNMdwPik2yrWipXCUPraSHMW5YaxbVwo6DtwBlheZLkVnxLTgQK7mEOlYAycJzth22Yen6AIT9SzAaCeVSEw+XjK12cQn+LXW5XnMNOfYwsBnMpVXlSshrbbPH3Gg0zu10Fd+1NVdXx6UiM0fxOBCZ7J4H7JfHUWaSTb1RsiFZLHZQcHIsWI6Z0KxEbAgMBAAECggEAVgCUhhRgFV4KsR2TGgAA20dCMg/RA5sdhc0mhb+Zg0sgSNU4Gmyd2YzftkCw6TDjfPKc9MtfDSGWCWy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RlMusOlkzwmaNkmO1DWg0Lp2GdZ/gxZl38KYyzAplg0tQRXG2JwW5kHfweg7XJcXjg==";
    // 编码格式
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlyFDWDhpfzRGLhYG9tCj/7fH2DDRhr7D9DkvGO1leKQSVNzDsKWYbp60oM2TBMS36rp40kN1NzeD21gyna/PvQT3m9RFQu7Y2zKZRD09QWoheBt1288ldB3wO5FjbHmdg6qp3B4Y61k+VFDl1U0d7INJ9bxvc1CHKRiHIzYmPr6QqFhOTeP+Ih23xNvZ8Z2XCcdt7r1Rjohj4LaI0ELaauCeO0+n8+6jmmUXvQ/jfD+aZEFii9DM+fw44yv0Ndga2MpN9LSU/gS7GZFigEu6aPnm9RpTZjvkoIBvnCvX279qBoItG4YfNh2MQ4nKhrmtTYvi2v3Q1INo8B+q/KodmQIDAQAB";
    // 沙箱路径接口，正是路径应为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    // 参数返回格式
    private final String FORMAT = "JSON";
    // 签名方式
    private final String SIGN_TYPE = "RSA2";
    // 支付宝异步通知路径，付款完毕后会异步调用本项目的方法，必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyURL";
    // 支付宝同步通知路径，也就是当付款完毕后跳转本项目的页面，可以不是公网地址
    private final String RETURN_URL = "http://localhost/order/commit";


    @RequestMapping("alipay")
    public void alipay(HttpServletResponse response, Double orderAmount) throws IOException {



        // 实例化客户端,填入所需参数
        // 网关地址 应用标识 应用私钥 传输格式 编码格式 支付宝公钥 签名类型
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Double.toString(orderAmount);
        //订单名称，必填
        String subject ="医疗项目订单";
        //商品描述，可空
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            //支付完成生成订单表
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + CHARSET);
        response.getWriter().write(form);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ResponseBody
    @PostMapping("/alipay/item")
    public AjaxResult item(@RequestBody(required = false)Map<String,Object> obj){
        System.out.println(obj);
        Map<String,Object> map = (Map<String, Object>) obj.get("ordercharge");
        Integer orderAmount = (Integer) map.get("orderAmount");
        HisOrderCharge ordercharge = new HisOrderCharge();
        Double amount = Double.valueOf(orderAmount);
        ordercharge.setChId((String) map.get("chId"));
        ordercharge.setRegId((String) map.get("regId"));
        ordercharge.setPatientName((String) map.get("patientName"));
        ordercharge.setOrderAmount(amount);
        System.out.println(ordercharge);
       System.out.println(ordercharge);

        String orderId = "DD"+ new Random().nextInt(100);
        String payPlatFormId = "ZF"+UUID.randomUUID().toString();
        ordercharge.setOrderId(orderId);
        ordercharge.setOrderStatus("1");
        ordercharge.setPayPlatformId(payPlatFormId);
        List<Map<String,Object>> mapList = (List<Map<String, Object>>) obj.get("data");
        List<HisOrderChargeItem> orderChargeItemList = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : mapList) {
            HisOrderChargeItem hisOrderChargeItem = new HisOrderChargeItem( );
            hisOrderChargeItem.setItemId((String) stringObjectMap.get("itemId"));
            hisOrderChargeItem.setCoId((String) stringObjectMap.get("coId"));
            hisOrderChargeItem.setItemName((String) stringObjectMap.get("itemName"));
            hisOrderChargeItem.setItemPrice(Double.valueOf((Integer) stringObjectMap.get("itemPrice")) );
            hisOrderChargeItem.setItemNum((Integer) stringObjectMap.get("itemNum"));
            hisOrderChargeItem.setItemType((String) stringObjectMap.get("itemType"));
            hisOrderChargeItem.setItemAmount(Double.valueOf((Integer) stringObjectMap.get("itemAmount")));
            orderChargeItemList.add(hisOrderChargeItem);
        }
        return payService.addOrder(ordercharge,orderChargeItemList);



    }
}


